package com.qq.manager;

import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class SimpleTxManager {
    private final DataSource dataSource;
    private static final ThreadLocal<Connection> CTX = new ThreadLocal<>();

    public SimpleTxManager(DataSource ds) {
        this.dataSource = ds;
    }

    //获取连接
    public void begin(boolean readOnly) throws SQLException {
        if (CTX.get() != null) return;
        Connection conn = dataSource.getConnection();
        conn.setAutoCommit(false);
        conn.setReadOnly(readOnly);
        CTX.set(conn);
    }

    //提交事务
    public void commit() throws SQLException {
        Connection conn = CTX.get();
        if (conn != null) {
            try { conn.commit(); } finally { cleanup(conn); }
        }
    }

    //回滚事务
    public void rollback() throws SQLException {
        Connection conn = CTX.get();
        if (conn != null) {
            try { conn.rollback(); } finally { cleanup(conn); }
        }
    }

    public static Connection currentConnection() {
        return CTX.get();
    }

    private void cleanup(Connection conn) throws SQLException {
        conn.setReadOnly(false);
        CTX.remove();
        conn.close();
    }
}
